package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小旭
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        String key = CACHE_TYPE_KEY;
        //1.先去redis中获取redis数据
        String typeJSON= stringRedisTemplate.opsForValue().get(key);
        //2.存在，返回查询结果
        if(typeJSON!=null){
            List<ShopType> shopTypes = JSONUtil.toList(typeJSON, ShopType.class);
            return Result.ok(shopTypes);
        }
        //3.不存在，去数据库中查询
        List<ShopType> shopTypes = this.query().orderByAsc("sort").list();
        //4.不存在，返回给404
        if(shopTypes.isEmpty()){
            return Result.fail("页面不存在");
        }
        //5.存在，将查询结果存入redis中
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopTypes));
        //6.返回查询结果
        return Result.ok(shopTypes);
    }
}
